package cn.tianya.irock.util;

import java.io.Writer;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;

public class JSONUtil {
	
	private static XStream xstream = new XStream(new JettisonMappedXmlDriver());//FormatedJsonHierarchicalStreamDriver
	
	public static String toJSONString(Object obj, List<Class> alias) {
		//xstream.alias(obj.getClass().getSimpleName(), obj.getClass());
		for (Class clz : alias) {
			xstream.alias(clz.getSimpleName(), clz);
		}
		return xstream.toXML(obj);
	}
	
	public static String toJSONString(Object obj) {
		return xstream.toXML(obj);
	}
	
	public static void toJSONString(Object obj, Writer out) {
		xstream.toXML(obj, out);
	}
	
	public static String toSimpleString(Object obj) {
		JSONObject json = new JSONObject(obj);

		return json.toString();
	}
	
	public static String arrayToSimpleString(List<?> obj) {
		JSONArray json = new JSONArray(obj);
		
		return json.toString();
	}
	
	public static Object fromJSONString(String str) {
		return xstream.fromXML(str);
	}
	
	public static Object fromJSONString(String str, Class<?> type) {
		xstream.alias(type.getSimpleName(), type);
		return xstream.fromXML(str);
	}
}
